﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Op.Common;
using YouWei.Op.Models.Customer;
using YouWei.Utility.Logging;

namespace YouWei.Op.Controllers
{
    public class CustomerController : BaseController
    {
        private CustomerService _service = new CustomerService();
        private UserCardService cardService = new UserCardService();
        private UserCardContentService cardContentService = new UserCardContentService();
        private CardContentRelaService relaService = new CardContentRelaService();
        private PaymentService payService = new PaymentService();

        private string url = Utility.ConfigHelper.GetAppSettingValue("CommentImageServerUrl");

        public ActionResult Index()
        {
            var userId = GetParam("userId");
            ViewBag.UserID = userId;
            return View();
        }
        [HttpPost]
        public PartialViewResult ParList(CustomerSearchModel model)
        {
            try
            {
                var pageIndex = Convert.ToInt32(GetParam("page"));
                var pageSize = GetPageSize();
                var page = _service.Pages(pageIndex, pageSize, model);
                ViewBag.Total = page.total;
                ViewBag.PageIndex = pageIndex;
                ViewBag.PageSize = pageSize;
                return PartialView(page.rows);
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                return PartialView();
            }
        }
        public ActionResult CustomerInfo()
        {
            var id = Convert.ToInt32(GetParam("id"));
            var model = _service.Single(id);
            return View(model);
        }

        #region 客户卡

        [AllowAnonymous]
        public ActionResult CardList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetCardList(ReqUserCardCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<UserCardDto> page = cardService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.IconUrl = string.Format("{0}/{1}", url, item.Icon);
            }
            return ReturnResult(page);
        }

        public ActionResult CardEdit()
        {
            UserCard info = new UserCard();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = cardService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveCard(ReqUserCard reqModel)
        {
            var res = new ResultData<string>();
            UserCard info = null;
            if (reqModel.CardId > 0)
            {
                info = cardService.Single(reqModel.CardId);
                info.LastUpdateDate = DateTime.Now;
                info.LastUpdateUser = CurrentUser.UserId;
            }
            else
            {
                info = new UserCard();
                info.CreatedDate = DateTime.Now;
                info.CreateUser = CurrentUser.UserId;
                info.IsActive = 1;
            }

            info.Name = reqModel.Name;
            info.Icon = reqModel.Icon;
            info.Level = reqModel.Level;
            info.Price = reqModel.Price;
            info.PayPrice = reqModel.PayPrice;
            info.DiffPrice = reqModel.DiffPrice;
            info.Description = reqModel.Description;
            try
            {
                if (info.CardId <= 0)
                {
                    cardService.Insert(info);
                }
                else
                {
                    cardService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelCard(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            UserCard info = cardService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.LastUpdateDate = DateTime.Now;
                info.LastUpdateUser = CurrentUser.UserId;
                cardService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取有效客户卡
        /// </summary>
        /// <returns></returns>
        public ContentResult GetActiveCardList()
        {
            List<UserCard> list = cardService.GetList();
            return ReturnResult(list);
        }
        #endregion

        #region 客户卡内容

        [AllowAnonymous]
        public ActionResult CardContentList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetCardContentList(ReqUserCardContentCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<UserCardContentDto> page = cardContentService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.ImgDetailUrl= string.Format("{0}/{1}", url, item.DetailUrl);
                item.IconUrl = string.Format("{0}/{1}", url, item.Icon);
            }
            return ReturnResult(page);
        }

        public ActionResult CardContentEdit()
        {
            UserCardContent info = new UserCardContent();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = cardContentService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveCardContent(ReqUserCardContent reqModel)
        {
            var res = new ResultData<string>();
            UserCardContent info = null;
            if (reqModel.CardContentId > 0)
            {
                info = cardContentService.Single(reqModel.CardContentId);
                info.LastUpdateDate = DateTime.Now;
                info.LastUpdateUser = CurrentUser.UserId;
            }
            else
            {
                info = new UserCardContent();
                info.CreatedDate = DateTime.Now;
                info.CreateUser = CurrentUser.UserId;
                info.IsActive = 1;
            }

            info.Name = reqModel.Name;
            info.Icon = reqModel.Icon;
            info.Price = reqModel.Price;
            info.CardType = reqModel.CardType;
            info.Category = reqModel.Category;
            info.DetailUrl = reqModel.DetailUrl;
            info.UrlName = reqModel.UrlName;
            info.Url = reqModel.Url;
            info.PayUrlName = reqModel.PayUrlName;
            info.PayUrl = reqModel.PayUrl;
            info.Description = reqModel.Description;
            try
            {
                if (info.CardContentId <= 0)
                {
                    cardContentService.Insert(info);
                }
                else
                {
                    cardContentService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelCardContent(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            UserCardContent info = cardContentService.Single(id);
            if (info != null)
            {
                info.IsActive = 0;
                info.LastUpdateDate = DateTime.Now;
                info.LastUpdateUser = CurrentUser.UserId;
                cardContentService.Update(info);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        /// <summary>
        /// 获取有效客户卡内容列表
        /// </summary>
        /// <returns></returns>
        public ContentResult GetActiveContentList()
        {
            List<UserCardContent> list = cardContentService.GetList();
            return ReturnResult(list);
        }

        #endregion

        #region 客户卡内容关联
        [AllowAnonymous]
        public ActionResult CardContentRelaList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetCardContentRelaList(ReqCardContentRelaCondition model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<UserCardContentRela> page = relaService.GetPages(pageIndex, pageSize, model);
            foreach (var item in page.rows)
            {
                item.DetailImageUrl = string.Format("{0}/{1}", url, item.DetailUrl);
            }
            return ReturnResult(page);
        }

        public ActionResult CardContentRelaEdit()
        {
            UserCardContentRela info = new UserCardContentRela();
            int id = Utility.EConvert.ToInt(GetParam("id"), 0);
            if (id > 0)
            {
                info = relaService.Single(id);
            }
            return View(info);
        }

        /// <summary>
        /// 保存用户
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ContentResult SaveCardContentRela(ReqCardContentRela reqModel)
        {
            var res = new ResultData<string>();
            UserCardContentRela info = null;
            if (reqModel.CardContentRelaID > 0)
            {
                info = relaService.Single(reqModel.CardContentRelaID);
                info.LastUpdateDate = DateTime.Now;
                info.LastUpdateUser = CurrentUser.UserId;
            }
            else
            {
                info = new UserCardContentRela();
                info.CreatedDate = DateTime.Now;
                info.CreateUser = CurrentUser.UserId;
            }
            if (reqModel.Diff > 1)
            {
                res.status = -1;
                res.message = "折扣不能大于1";
                return ReturnResult(res);
            }
            info.Diff = reqModel.Diff;

            //   var cardContent = cardContentService.SingleOrDefault(reqModel.CardContentId);
            //如果有折扣，则自动计算折扣之后的价格
            // if (info.Diff > 0)
            // {
            info.Price = reqModel.Price;
           // }el

            info.DetailUrl = reqModel.DetailUrl;
            info.CardId = reqModel.CardId;
            info.CardContentId = reqModel.CardContentId;
            info.Description = reqModel.Description;
            try
            {
                if (info.CardContentRelaID <= 0)
                {
                    relaService.Insert(info);
                }
                else
                {
                    relaService.Update(info);
                }
                res.message = "成功";
                res.status = 0;
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
                res.message = "添加失败";
                res.status = -1;

            }
            return ReturnResult(res);
        }

        /// <summary>
        /// 删除卡
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ContentResult DelCardContentRela(int id)
        {
            ResultData<bool> rData = new ResultData<bool>();
            if (id < 1)
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                return ReturnResult(rData);
            }
            UserCardContentRela info = relaService.Single(id);
            if (info != null)
            {
                relaService.Delete(info.CardContentRelaID);
                rData.status = 0;
                rData.data = true;
            }
            else
            {
                rData.status = -1;
                rData.message = "当前数据不存在";
                rData.data = false;
            }
            return ReturnResult(rData);
        }

        #endregion

        #region 客户卡支付记录

        [AllowAnonymous]
        public ActionResult PayRecordList()
        {
            return View();
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ContentResult GetPayRecordList(ReqPayment model)
        {
            int pageIndex = GetPageIndex();
            int pageSize = GetPageSize();
            Page<PaymentDto> page = payService.GetPages(pageIndex, pageSize, model);
            return ReturnResult(page);
        }

        #endregion
    }
}